package com.server.chart;

import com.config.BasesSource.DynamicDataSourceContextHolder;
import com.dao.chart.ChartsConfigMapper;
import com.dao.chart.ShowChartsMapper;
import com.model.bo.ChartsColumnConfig;
import com.model.bo.Screen;
import com.model.bo.ScreenStr;
import com.model.pojo.RepCode;
import com.model.pojo.RepEntity;
import com.model.vo.configVo.PopulationInfo;
import com.model.vo.dataVo.PopAndIndDataInfo;
import com.util.ScreenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.*;

@Service
public class ShowPopulationService {
    @Autowired
    ChartsConfigMapper chartsConfigMapper;
    @Autowired
    ShowChartsMapper showChartsMapper;
    @Autowired
    GetChartsDataUtilService getChartsDataUtilService;
    @Autowired
    ScreenUtil screenUtil;
    @Autowired
    ChartsUtilService chartsUtilService;

    public RepEntity showPopulation(PopulationInfo populationInfo, String token, int dashId) throws SQLException {
        if (populationInfo == null || "".equals(populationInfo)){
            return new RepEntity(RepCode.Null);
        }
        PopAndIndDataInfo popAndIndDataInfo = new PopAndIndDataInfo();
        //取表名
        int id = populationInfo.getId();
        //获取列配置
        ChartsColumnConfig chartsColumn = chartsConfigMapper.getChartsColumn(id);
        if (chartsColumn == null || "".equals(chartsColumn)){
            return new RepEntity(RepCode.Null);
        }
        String style = chartsColumn.getChartStyle();
        String config = chartsColumn.getChartConfig();
        popAndIndDataInfo.setChartsColumnConfig(chartsColumn);

        String tableName = chartsUtilService.getSqlStr(token, id, dashId);
        if ("".equals(tableName)){
            return new RepEntity(RepCode.NoAuthority);
        }

        int baseId = getChartsDataUtilService.getBaseId(id);
        System.out.println("切换数据库"+String.valueOf(baseId));

        try{
            if (!DynamicDataSourceContextHolder.isContainsDataSource(String.valueOf(baseId))) {
                //joinPoint.getSignature() ：获取连接点的方法签名对象
                System.out.println("数据源 " + String.valueOf(baseId) + " 不存在使用默认的数据源 -> ");
                return new RepEntity(RepCode.DataSourceNull);
            } else {
                System.out.println("使用数据源：" + String.valueOf(baseId));
                DynamicDataSourceContextHolder.setDataSourceType(String.valueOf(baseId));
            }
            List<String> groupByList = populationInfo.getGroupByList();  //分组

        //取目标列和分析运算符
            String columnName = populationInfo.getColumnName();
            List<String> operators = populationInfo.getOperatorList();
            Map<String, Double> targetData = new HashMap<>();  //存放结果集
            Double value = null;                 //MAP的值

            //取筛选列表
            List<Screen> screens = populationInfo.getFilters();
            String screen = "";
            String screenStr = "";
            ScreenStr str = new ScreenStr();
            if ("".equals(screens) || screens == null || screens.size() == 0){
                screen = "";
                screenStr = "";
            }else {
                str = screenUtil.screensUtil(screens, "", "");
                screen = str.getRet();
                StringBuilder sb = new StringBuilder(screen);
                screenStr = String.valueOf(sb .replace(1, 5, "where "));
            }

        //无分组
        if (groupByList.size() == 0) {
            Iterator operatorsList = operators.iterator();
            while (operatorsList.hasNext()) {
                String operator = String.valueOf(operatorsList.next()).toUpperCase();
                if ("75TH".equals(operator)) {
                    String calculation = "MEDIAN";
                    Double median = showChartsMapper.getColumnDev(tableName, columnName, calculation, screenStr);
                    calculation = "MAX";
                    Double max = showChartsMapper.getColumnDev(tableName, columnName, calculation, screenStr);
                    value = showChartsMapper.getValue(tableName, columnName, calculation, median, max);
                } else if ("25TH".equals(operator)) {
                    String calculation = "MEDIAN";
                    Double median = showChartsMapper.getColumnDev(tableName, columnName, calculation, screen);
                    calculation = "MIN";
                    Double min = showChartsMapper.getColumnDev(tableName, columnName, calculation, screenStr);
                    value = showChartsMapper.getValue(tableName, columnName, calculation, min, median);
                } else if ("PERCENT".equals(operator)) {
                    value = 1.00;
                } else {
                    value = showChartsMapper.getColumnData(tableName, columnName, operator, screenStr);
                }
                targetData.put(operator, value);
            }
            popAndIndDataInfo.setValueList(targetData);
            return new RepEntity(RepCode.success, popAndIndDataInfo);
            //有分组
        }else {
            String listOne = groupByList.get(0);

            Iterator operatorsList = operators.iterator();
            //获取常规运算列
            List<String> operatorColumn = new ArrayList<>();
            //获取25th,75th算符
            List<String> operatorOther = new ArrayList<>();

            String next = null;
            while (operatorsList.hasNext()){
                next = String.valueOf(operatorsList.next()).toLowerCase();

                System.out.println("next:"+next);
                //计算25th,75th,和百分比
                if (next.toUpperCase() == "PERCENT" || "PERCENT".equals(next.toUpperCase())){
                    System.out.println("走这里了吗？"+ next);
                    String op = "count(" + columnName + ")/(select count(1) from " + tableName + ") "+ next;
                    operatorColumn.add(op);
                }else if ("25th".equals(next) || "75th".equals(next)){
                    operatorOther.add(next);
                }else {
                    String op = next + "(" + columnName + ") as " + next.toLowerCase();
                    operatorColumn.add(op);
                }
            }

            String groups = groupByList.toString();
            String groupBy = getString(groups);

            String oprs = operatorColumn.toString();
            String opr = getString(oprs);

            //存放正常值
            List<LinkedHashMap<String, Object>> valueList = new ArrayList<>();

            //存放25th,75th
            List<LinkedHashMap<String, Object>> valueListTh = new ArrayList<>();

            Iterator thList = operatorOther.iterator();
            while (thList.hasNext()){
                String oprTh = (String) thList.next();
                String fOpertion = "";
                String aOpertion = "";
                if ("25th".equals(oprTh)){
                    fOpertion = "min";
                    aOpertion = "median";
                }else if ("75th".equals(oprTh)) {
                    fOpertion = "median";
                    aOpertion = "max";
                }
                valueListTh = showChartsMapper.getGroupByValueTh(groupBy, columnName, tableName, listOne, screen, fOpertion, aOpertion);

            }

            valueList = showChartsMapper.getGroupByValue(groupBy, opr, tableName, listOne, screenStr);
            valueList.addAll(valueListTh);
            System.out.println("valueList:"+ valueList);
            popAndIndDataInfo.setValueList(valueList);
            return new RepEntity(RepCode.success, popAndIndDataInfo);
        }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("异常");
            return new RepEntity(RepCode.erro);
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    public String getString(String str){
        String st1 = "[";
        String st2 = "]";
        String strA = str.replace(st1, "");
        String strB = strA.replace(st2, "");
        System.out.println("str:"+ strB);
        return strB;
    }
}
